package cn.mandifal.seller.controller;
import cn.mandifal.pojo.DpGoods;
import cn.mandifal.pojo.DpItem;
import cn.mandifal.pojo.GoodsCombine;
import cn.mandifal.seller.service.GoodsManagementService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import entity.PageResult;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.List;

/**
 * 商家商品管理控制层
 * @author shun
 */
@RestController
@RequestMapping("/goodsManagementController")
public class GoodsManagementController {
    @Reference
    private GoodsManagementService goodsManagementService;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private Destination queueSolrDestination;
    @Autowired
    private  Destination queueSolrDeleteDestination;
    @Autowired
    private Destination topicPageDestination;
    @Autowired
    private Destination topicPageDeleteDestination;

    /**
     * 模糊查询，无条件时为查询全部
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @param dpGoods 商品
     * @return 返回分页结果
     */
    @RequestMapping("/search")
    public PageResult search(int pageNum, int pageSize, @RequestBody DpGoods dpGoods){
        dpGoods.setSellerId(SecurityContextHolder.getContext().getAuthentication().getName());
        return goodsManagementService.search(pageNum,pageSize,dpGoods);
    }

    /**
     * 更新商品信息，提交审核
     * @param ids 商品 id
     * @param status 商品装填
     * @return 返回结果
     */
    @RequestMapping("/updateAuditStatus")
    public Result updateAuditStatus(Long[] ids,String status){
        try {
            //只有未申请的才能提交申请
            for (Long id:ids) {
                //得到商品组合实体
                GoodsCombine goodsCombine = goodsManagementService.findOne(id);
                //如果spu审核状态不为 0，则不允许提交审核
                System.out.println("-----------------------");
                if(! "0".equals(goodsCombine.getDpGoods().getAuditStatus())){
                    System.out.println("--------------------------");
                    return Result.failed("存在已提交审核的商品");
                }
            }
            goodsManagementService.updateAuditState(ids,status);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 添加商品 spu ,商品详情及 sku
     * @param goodsCombine 商品组合实体
     * @return 返回执行结果
     */
    @RequestMapping("/add")
    public Result add(@RequestBody GoodsCombine goodsCombine){
        //设置商家 id
        String sellerName = SecurityContextHolder.getContext().getAuthentication().getName();
        goodsCombine.getDpGoods().setSellerId(sellerName);
        try {
            goodsManagementService.add(goodsCombine);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 查询商品及详情
     * @param id 商品 id
     * @return 返回组合实体
     */
    @RequestMapping("/findOne")
    public GoodsCombine findOne(Long id){
        return goodsManagementService.findOne(id);
    }

    /**
     *  更新商品信息,只能在下架情况下更新
     * @param goodsCombine 商品组合实体
     * @return 返回结果
     */
    @RequestMapping("/update")
    public Result update(@RequestBody GoodsCombine goodsCombine){
        //判断当前商家修改的商品是否是此商家的商品，避免漏洞
        String sellerId = SecurityContextHolder.getContext().getAuthentication().getName();
        if (! goodsCombine.getDpGoods().getSellerId().equals(sellerId) ){
            return Result.failed();
        }
        //如果商品状态处于上架，则不允许修改
        if ( "1".equals(goodsCombine.getDpGoods().getIsMarketable()) ){
            return Result.failed("请先下架商品");
        }
        try {
            goodsManagementService.update(goodsCombine);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 逻辑删除商品
     * @param ids 商品 id
     * @return 返回结果
     */
    @RequestMapping("/delete")
    public Result delete(@RequestBody Long[] ids) {
        try {
            goodsManagementService.delete(ids);
            //从 solr 索引库中删除
            jmsTemplate.send(queueSolrDeleteDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createObjectMessage(ids);
                }
            });
            System.out.println("------------- 导入activemq删除 solr 库中数据成功 -------------");
            //删除商品 sku 详情页面
            jmsTemplate.send(topicPageDeleteDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createObjectMessage(ids);
                }
            });
            System.out.println("--------------导入 activemq 中删除商品 sku 详情页数据成功 ---------------");
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 上架商品，并导入 solr 库
     * @param ids 待上架的商品 id
     * @return 返回结果
     */
    @RequestMapping("/putAway")
    public Result putAway(@RequestBody Long[] ids){
        //判断每一个商品是否通过审核
        for (Long id:ids) {
            GoodsCombine one = goodsManagementService.findOne(id);
            //如果商品未通过审核则不允许上架
            if (! "2".equals(one.getDpGoods().getAuditStatus())){
                return Result.failed("存在审核未通过的商品");
            }
        }
        try {
            goodsManagementService.putAway(ids);
            //导入上架的商品
            List<DpItem> itemList = goodsManagementService.findItemListByGoodsIdAndStatus(ids, "1");

            //更新 solr 库
            final String jsonString = JSON.toJSONString(itemList);
            jmsTemplate.send(queueSolrDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(jsonString);
                }
            });
            System.out.println("------------导入 activemq 插入 solr 库中数据成功--------------");
            //循环创建商品详情页
            for (Long goodsId:ids) {
                jmsTemplate.send(topicPageDestination, new MessageCreator() {
                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        return session.createTextMessage(goodsId+"");
                    }
                });
            }
            System.out.println("------------导入 activemq 创建商品 sku 详情页数据成功--------------");
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 下架商品
     * @param ids 待下架的商品 id
     * @return 返回结果
     */
    @RequestMapping("/soldOut")
    public Result soldOut(@RequestBody Long[] ids){
        //判断每一个商品是否通过审核
        for (Long id:ids) {
            GoodsCombine one = goodsManagementService.findOne(id);
            //如果商品未通过审核则不允许下架
            if (! "2".equals(one.getDpGoods().getAuditStatus())){
                return Result.failed("存在审核未通过的商品");
            }
        }
        try {
            goodsManagementService.soldOut(ids);
            //从 solr 索引库中删除
            jmsTemplate.send(queueSolrDeleteDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createObjectMessage(ids);
                }
            });
            System.out.println("------------- 导入 activemq 删除 solr 库中数据成功 -------------");
            //删除商品 sku 详情页面
            jmsTemplate.send(topicPageDeleteDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createObjectMessage(ids);
                }
            });
            System.out.println("--------------导入 activemq 中删除商品 sku 详情页数据成功 ---------------");
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

}
